package com.example;

import com.example.anno.EnableMapper;
import com.example.postprocessor.Fruit;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import outside.OutConfiguration;
import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@ComponentScan(basePackages = "com.example",
        // useDefaultFilters = false,
        includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Fruit.class)
) // 扫描com.example包及其子包中的组件
@Import({OutConfiguration.class})
@EnableMapper(basePackages = "mapper")
@MapperScan("com.example.mapper")
public class AppConfig {
    // 这个类替代了传统的applicationContext.xml

    /* 1. 数据源 */
    @Bean
    public DataSource dataSource() {
        HikariConfig cfg = new HikariConfig();
        cfg.setDriverClassName("org.h2.Driver");
        cfg.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MODE=MySQL");
        cfg.setUsername("sa");
        cfg.setPassword("");
        return new HikariDataSource(cfg);
    }

    /* 2. SqlSessionFactoryBean —— Spring-MyBatis 整合入口 */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource ds) throws IOException {
        SqlSessionFactoryBean f = new SqlSessionFactoryBean();
        f.setDataSource(ds);

        // 别名包
        f.setTypeAliasesPackage("com.example.entity");

        // XML 位置
        f.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources("classpath*:mapper/*.xml"));

        // 可选 MyBatis 设置
        org.apache.ibatis.session.Configuration c = new org.apache.ibatis.session.Configuration();
        c.setMapUnderscoreToCamelCase(true);
        c.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
        f.setConfiguration(c);

        return f;
    }

    /* 3. 扫描 Mapper 接口（生成代理） */
    @Bean
    public MapperScannerConfigurer mapperScanner() {
        MapperScannerConfigurer scan = new MapperScannerConfigurer();
        scan.setBasePackage("com.example.mapper");
        // 如果上面 SqlSessionFactoryBean 名字不是 sqlSessionFactory 需显式指定
        // scan.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return scan;
    }

    /* 4. 事务管理器 */
    @Bean
    public DataSourceTransactionManager transactionManager(DataSource ds) {
        return new DataSourceTransactionManager(ds);
    }


}